<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in arr" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.username }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="bianji(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          id: '1',
          username: 'Tom',
          age: 19,
          gender: '男',
        },
        {
          id: '2',
          username: 'Jone',
          age: 21,
          gender: '女',
        },
      ],
      username: '',
      age: '',
      gender: '',
      aid: '',
    };
  },
  methods: {
    del(id) {
      this.arr = this.arr.filter((item) => item.id !== id);
    },

    add() {
      if (this.username && this.age && this.gender) {
        if (this.aid) {
          //  console.log(1);
          // console.log(this.username);
          // console.log(this.age);
          const arr2 = this.arr.filter((item) => item.id === this.aid);
          arr2[0].username = this.username;
          arr2[0].age = this.age;
          arr2[0].gender = this.gender;
        } else {
          const obj = {
            id: this.arr.length + 1,
            username: this.username,
            age: this.age,
            gender: this.gender,
          };
          this.arr.push(obj);
          // this.arr = { ...this.arr, obj };
        }
      }
      else {
        alert('请输入完整内容')
      }
    },
    bianji(id) {
      const arr1 = this.arr.filter((item) => item.id === id);
      // console.log(arr1);
      if (id) {
        this.username = arr1[0].username;
        this.age = arr1[0].age;
        this.gender = arr1[0].gender;
        this.aid = id;
      }
    },
  },
};
</script>
